/**
 * Copyright (C), 2015, 上海赛可电子商务有限公司
 * Author:   康明飞
 * Date:     2016-5-31
 * Description: 通用的js逻辑
 */
;(function(){
	var suggestNode = document.getElementById("attendSymbol"),
		recommendItem = '',
		oSearchFormInput = $("#attendSymbol"),
		oSearchFormRecommend = $(".recommend-cont");
	$.ajax({
		url:'/mall/hotSearch.htm',
		type:'get',
		dataType:'json',
		success:function(data){
			if(suggestNode){
				var arg = {
				    text: "请输入品牌、级别、车系、车型",
				    header: null,
				    body: ["searchWord"],
				    max: 10,
				    target: "_self",
				    dataurl: "/mall/searchNotice.htm?prefix={#KEY}&jsonP={#NAME}",
				    hotSearchList: data,
				    callback: function(arg) {}
				};
				$.each(data,function(key,val){
					if(key < 3){
						recommendItem += "<a href=/multisearch/search.htm?cat=1&kwd="+encodeURI(data[key].searchWord)+">"+data[key].searchWord+"</a>";
					}
				});
				oSearchFormRecommend.html(recommendItem);

				new MallSuggest("attendSymbol", arg);//搜索联想功能调用

				oSearchFormInput.on("focus",function(){
					oSearchFormRecommend.hide();
				});
				oSearchFormInput.on("blur",function(){
					if(oSearchFormInput.val()==="" ){
						oSearchFormRecommend.show();
					}
				});
			}
		}
	});
})();
$(function(){
	initCityList(cityJson);
	//16-01-26添加城市监控代码 CA='+monitorVersion+"_cm-home_pc_topnav_c2$城市$"+cityName
	$('#cityPos').on("click",function(){
		var cityname = $("#currentCity").attr("name");
		var cityid = $("#currentCity").attr("id");
		var img = new Image(1,1),
		ca=monitorVersion+"_cm-home_pc_topnav_c2$城市$"+cityname;
		img.src =  ('https:' == document.location.protocol ? 'https' : 'http')+'://data.chexiang.com/ca.gif?'+'id='+cityid+'&ca='+ca+"&_v="+new Date();
	});
	// 判断用户是否已登录
	$.ajax({
		url:"/common/head.htm",
		dataType: "json",
		cache: false,
		success: function(data) {
			if(data){
				var favorNode = $("#mall-my");
				favorNode.attr({"href":favorNode.attr("login-href"),"target":"_blank"});
				$("#box01").hide().siblings("#box02").show();
				$("#box02").children().eq(0).html(data.greetings + '，<span title="'+data.greetings+","+data.memberCenterInfo.defaultAccount+'">'+data.realName+'</span>');
				var loginoutUrl = logoutBase + "?service=" + encodeURIComponent(MALL.base) + "&systemType=MAIN";
				$("#userCenter .group").append("<a href='"+loginoutUrl+"' target='_self'>退出</a>");
			}else{
				$("#box01").show().siblings("#box02").hide();
			}
		}
	});
	
	$('.mobileview').hover(function(){
		$('.go-mobile',this).show();
  	},function(){
  		$('.go-mobile',this).hide();
	});

	$(".login-bind").on("click", function(){
		var backUrl = window.location.href;
		window.location.href = accountBase + "/account/login.htm?backUrl=" + encodeURIComponent(backUrl);
		return false;
	});
	$(".register-bind").on("click", function(){
		var backUrl = window.location.href;
		window.location.href = accountBase + "/account/m_register.htm?backUrl=" + encodeURIComponent(backUrl);
		return false;
	});
	showDrop($('#userCenter'),$('.user-hd'),"user-cur",$('.group'));	
	$(document.body).on('click',function(e){
		$('#cityPos').removeClass('city-cur');
		$('#citychage').hide();
	});
	$('#cityPos').on('click',function(){
		if($(this).hasClass('city-cur')){
			$(this).removeClass('city-cur');
			$('#citychage').slideUp();
			return false;
		}
		$(this).addClass('city-cur');
		$('#citychage').slideDown();
		return false;
	});

	function showDrop(handleDom,child,onClass,dropDom){
		var timeID=null;
		handleDom.mouseover(function(){
			clearTimeout(timeID);
			child.addClass(onClass);
			dropDom.show();
		}).mouseout(function(){
			timeID=setTimeout(function(){
				dropDom.slideUp(200, function(){
				child.removeClass(onClass);
			});
			},500);
		});
	}
	// 城市切换
	function bindEventOnCityList(){
		var cityShow = $('#currentCity'),					// 显示城市
			cityList = $('#citychage');			     	  	// 城市列表
		// 选中城市
		cityList.on('click',"a", function(){
			var cityid = $(this).attr('cityid'),	// 城市id
				cityname = $(this).attr('name');	// 城市name
			var cache_cityId = _getCookie("city.id");
			if(cityid != cache_cityId){
				cityCookie(cityid, cityname);			// 更新cookie
				cityShow.attr({'cityid':cityid, 'name':cityname}).text(cityname);
				cityList.hide();
				if(location.href.indexOf("/list/")!= -1){
					location.href = location.href.replace(/^([\s\S]+-)(\d+)(-\d+-\d+-\d+\.html[\s\S]*?)$/ig,"$1"+cityid+"$3")
				}else if(location.href.indexOf("/product/")!= -1){
					location.href = "/mall/index.htm";
				}else{
					window.location.reload(true);	
				}
			}
		});
	};
	//Cookie Common Class
	function _getCookie(key) {
	    var result = document.cookie.match(new RegExp("(^| )" + key + "=([^;]*)"));
	    return result != null ? decodeURIComponent(result[2]) : null;
	}
	function _setCookie(key, value, expireDay) {
	    if (expireDay) {
	        var date = new Date();
	        date.setTime(date.getTime() + expireDay * 24 * 3600 * 1000);
	        document.cookie = key + "=" + encodeURIComponent(value) + ";path=/;expires=" + date.toGMTString();
	    } else {
	        document.cookie = key + "=" + encodeURIComponent(value) + ";path=/";
	    }
	}
	// 存储cookie
	function cityCookie(cityId, cityName){
		_setCookie("city.id",cityId,365);
		_setCookie("city.name",cityName,365);
	}
	function _arrayIsContain(arr,value){
	    var isContain = false;
	    var tempVal;
	    $.each(arr,function(index){
	        if($.isArray(arr)){
	            tempVal = arr[index];
	        }else{
	            tempVal = index;
	        }
	        if(value === tempVal){
	            isContain = true;
	            return false;  // 结束循环
	        }
	    });
	    return isContain;
	}
	// 设置当前用户公网ip所在的城市，如果不在8城市站则返回上海
	function setCityCookie(){
		var mallCity = [];
		for(var i=0,len=cityJson.length;i<len;i++){
			mallCity.push(cityJson[i].name.replace("市","").replace("地区","").replace("自治州",""));
		}
		var mallProvince = {
	        "上海":['上海'],
	        "江苏":['南京'],
	        "浙江":['杭州'],
	        "四川":['成都']
	    };
		var mainWebCityName=_getCookie("city_name");
		//主站的cookie不为空，并且在我们六个城市列表中的话
		if(mainWebCityName!=null&&_arrayIsContain(mallCity,mainWebCityName)){
			var mainWebCityId=_getCookie("city_id");
			cityCookie(mainWebCityId, mainWebCityName);
			$('#currentCity').attr({'cityid':mainWebCityId, 'name':mainWebCityName}).text(mainWebCityName);
		}else{
			// 获取所在城市
			$.getJSON("http://api.map.baidu.com/location/ip?ak=F454f8a5efe5e577997931cc01de3974&ip=&callback=?", function(data) {
				if(!data || data.length ==0 || data.status !=0) return;
				var cityInfo = data.address.split("|");
		        var city = cityInfo[2],
		            province = cityInfo[1];
		        if(!_arrayIsContain(mallCity,city)){
			        if(_arrayIsContain(mallProvince,province)){
			        	city = mallProvince[province][0];
			        }else{
			            city = "上海";
			        }
		        }
				// 根据城市名获取id
				$.getJSON("/common/getCityId.htm?cityName="+encodeURIComponent(city), function(data) {
					if(data){
						cityCookie(data.cityId, data.cityName);
					}
				});
			});
		}
	}
	function initCityList(data){
		//初始化页面加载时显示的城市
		var cityShow = $('#currentCity');		// 显示城市
		var cityId = _getCookie("city.id");
		var cityName = _getCookie("city.name");
		// 没有在cookie中获取到城市则在线获取
		if (cityId && cityName) {
			cityShow.attr({'cityid':cityId, 'name':cityName}).text(cityName);
		}else{
			cityShow.attr({'cityid':"310100", 'name':"上海"}).text("上海");
			setCityCookie();
		}
		var cityHtml=[];
		$.each(data,function(i,item){
			if(item.code&&item.name){
				var curStr="";
				if(item.code == cityId){
					curStr=" class=\"cur\"";
				}
				var cityName=item.name.replace("市","").replace("地区","").replace("自治州","");
				
				cityHtml.push('<a href="javascript:void(0);" target="_self" cityid="'+item.code+'" name="'+cityName+'" class="city-name"><span'+ curStr +'>'+cityName+'</span></a>');
			}
		});
		$("#citychage").html(cityHtml.join(""));
		bindEventOnCityList();
	}
	function showSideScreen(){
        $(".js_not_index").hover(function() {
            $(".fast-screen").show();
        }, function() {
            $(".fast-screen").hide();
        });
	}
	showSideScreen();
});
